import React, {Component} from 'react';
import {message, Button, Input} from 'antd';
import fetch from 'isomorphic-fetch';
import * as base from '../../common/BaseUrl';
import GameInfoCss from '../../css/GameInfoCss.css';
import GameInfoAddModal from './GameInfoAddModal';
import gameStore from '../../stores/GameStore';
import GameAction from '../../action/GameAction';
import GameInfoTable from './GameInfoTable';
import ActionDiv from "../userInfo/ActionDiv";
import GameInfoModal from "./GameInfoModal";
import {postFetch as postFetch} from '../../common/PostFetch';
import PropTypes from "prop-types";

let gameAction = new GameAction();

class GameInfo extends Component {
    constructor(props) {
        super(props);
        console.log(props.history);
        this.state = {
            dataSource: [],
            columns: [
                {
                    title: '序号',
                    dataIndex: 'id',
                    key: 'id',
                }, {
                    title: '游戏名称',
                    dataIndex: 'gameName',
                    key: 'gameName',
                }, {
                    title: '游戏类型',
                    dataIndex: 'gameType',
                    key: 'gameType',
                }, {
                    title: '游戏类型名称',
                    dataIndex: 'gameTypeName',
                    key: 'gameTypeName',
                }, {
                    title: 'Action',
                    key: 'action',
                    render: (text, record) => (
                        <span>
                            <Button onClick={() => this.goGameUpdateModal(event, record)}
                                    size="small">修改</Button>
                        </span>
                    ),
                }
            ],
            selectedRowKeys: [],
            pageSize: 10,
            pagination: {current: 1},
            searchName: '',
            visible: false,
            action: '',
            title: '',
            gameInfo: {},
            gameTypeInfo: [],
            newRandomKey: 1
        };
        this.goGameUpdateModal = this.goGameUpdateModal.bind(this);
        this.handleTableChange = this.handleTableChange.bind(this);
        this.onChangeSearchName = this.onChangeSearchName.bind(this);
        this.onChangeSearchName = this.onChangeSearchName.bind(this);
        this.deleteInfo = this.deleteInfo.bind(this);
        this.refresh = this.refresh.bind(this);
        this.selectGameTypeInfo = this.selectGameTypeInfo.bind(this);
        this.goGameModal = this.goGameModal.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        this.saveGameInfo = this.saveGameInfo.bind(this);
        this.saveFormRef = this.saveFormRef.bind(this);
        this.onSelectChange = this.onSelectChange.bind(this);
        this.showMessage = this.showMessage.bind(this);
    }


    componentDidMount() {
        this.refresh();
        this.selectGameTypeInfo();
    }

    selectGameTypeInfo() {
        let url = base.BaseUrl + 'react/gameInfo/selectGameTypeInfo';
        let formData = new FormData();
        fetch(url, {
            method: 'post',
            body: formData,
            header: base.headers,
            credentials: 'include',
            redirect: 'follow',
            mode: 'cors'
        }).then(res => res.json()).then(json => {
            this.setState({
                gameTypeInfo: json
            });
        }).catch(err => {
            console.log(err);
        });
    }

    refresh() {
        let gameName = this.state.searchName;
        let pageSize = this.state.pageSize;
        let pageNumber = this.state.pagination.current;
        let url = base.BaseUrl + "react/gameInfo/selectGameInfo";
        let formData = new FormData();
        formData.append("gameName", gameName);
        formData.append("pageSize", pageSize);
        formData.append("pageNumber", pageNumber);
        fetch(url, {
            method: 'post',
            body: formData,
            header: base.headers,
            credentials: 'include',
            redirect: 'follow',
            mode: 'cors'
        }).then(res => res.json()).then(json => {
            let total = json.total;
            //如果这边不定义会怎么样
            let pagination = this.state.pagination;
            pagination.total = total;
            pagination.current = json.pageNumber;
            let gameInfoList = json.gameInfoList;
            this.setState({
                dataSource: gameInfoList,
                pagination: pagination
            });
        }).catch(err => {
            console.log(err);
        });
    }

    goGameUpdateModal(event, record) {
        event.preventDefault();
        this.setState({
            visible: !this.state.visible,
            action: 'update',
            title: '修改游戏信息',
            gameInfo: record,
            newRandomKey: this.state.newRandomKey + 1
        });
    }

    goGameModal() {
        this.setState({
            visible: !this.state.visible,
            action: 'save',
            title: '新增游戏信息',
            gameInfo: {gameName: '', gameType: ''},
            newRandomKey: this.state.newRandomKey + 1
        });
    }

    saveGameInfo(action) {
        const form = this.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            let url;
            let formData = new FormData();
            if (action === 'update') {
                url = base.BaseUrl + "react/gameInfo/updateGameInfo";
                let id = this.state.gameInfo.id;
                formData.append('gameId', id);
            } else {
                url = base.BaseUrl + "react/gameInfo/saveGameInfo";
            }
            formData.append("gameName", values.gameName);
            formData.append("gameType", values.gameType);
            fetch(url, {
                method: 'post',
                body: formData,
                header: base.headers,
                credentials: 'include',
                redirect: 'follow',
                mode: 'cors'
            }).then(res => res.json()).then(json => {
                let messageType = 'error';
                let message = '保存失败';
                if (json) {
                    this.refresh();
                    form.resetFields();
                    this.setState({visible: false});
                    messageType = 'success';
                    message = '保存成功';
                }
                this.showMessage(messageType, message, 8);
            });
        });
    }

    saveFormRef(form) {
        this.form = form;
    }

    deleteInfo() {
        let selectedRowKeys = this.state.selectedRowKeys;
        let url = base.BaseUrl + 'react/gameInfo/deleteGameInfo';
        let formData = new FormData();
        formData.append("selectedRowKeys", selectedRowKeys);
        fetch(url, {
            method: 'post',
            body: formData,
            header: base.headers,
            credentials: 'include',
            redirect: 'follow',
            mode: 'cors'
        }).then(res => res.json()).then(json => {
            let messageType = 'error';
            let message = '游戏删除失败';
            if (json) {
                this.refresh();
                messageType = 'success';
                message = '游戏删除失败';
            }
            this.showMessage(messageType, message, 5);
        });
    }

    showMessage() {
        if (type == 'error') {
            message.error(message, time);
        } else {
            message.success(message, time);
        }
    }

    handleCancel() {
        this.setState({
            visible: !this.state.visible,
        });
    }

    handleTableChange(pagination, filters, sorter) {
        const pager = this.state.pagination;
        pager.current = pagination.current;
        this.setState({
            pagination: pager,
        });
        this.refresh();
    }

    onChangeSearchName(e) {
        this.setState({
            searchName: e.target.value
        })
    }

    onSelectChange(selectedRowKeys) {
        this.setState({
            selectedRowKeys: selectedRowKeys
        });
    }

    render() {
        const selectedRowKeys = this.state.selectedRowKeys;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        return (
            <div>
                <Input placeholder="input search text" style={{width: 200}} onChange={this.onChangeSearchName}/>
                <ActionDiv refresh={this.refresh} deleteInfo={this.deleteInfo}
                           goAddModal={this.goGameModal}/>
                <GameInfoTable dataSource={this.state.dataSource} columns={this.state.columns}
                               pagination={this.state.pagination} handleTableChange={this.handleTableChange}
                               rowSelection={rowSelection}/>
                <GameInfoModal newRandomKey={this.state.newRandomKey} visible={this.state.visible}
                               title={this.state.title}
                               saveGameInfo={this.saveGameInfo} action={this.state.action}
                               handleCancel={this.handleCancel} saveFormRef={this.saveFormRef}
                               gameInfo={this.state.gameInfo} gameTypeInfo={this.state.gameTypeInfo}/>
            </div>
        );
    }
}

export default GameInfo

